<!-- src/views/company/EnterpriseLayout.vue -->
<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useCompanyStore } from '../../store/company'
import { useAuthStore } from '../../store/auth'
import { ElMessageBox, ElMessage } from 'element-plus'
// 导入Element Plus图标组件
import {
  House,
  Briefcase,
  Document,
  Star,
  OfficeBuilding,
  Expand,
  Fold,
  UserFilled,
  SwitchButton,
  User
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const companyStore = useCompanyStore()
const authStore = useAuthStore()

const isCollapse = ref(false)
const userInfo = ref(null)
const profileComplete = ref(false)
const activeMenu = ref('')

// 侧边栏菜单项
const menuItems = [
  {
    index: '/company/dashboard',
    title: '仪表板',
    icon: House
  },
  {
    index: '/company/positions',
    title: '岗位管理',
    icon: Briefcase
  },
  {
    index: '/company/applications',
    title: '申请管理',
    icon: Document
  },
  {
    index: '/company/evaluations',
    title: '评分管理',
    icon: Star
  },
  {
    index: '/company/profile',
    title: '企业信息',
    icon: OfficeBuilding
  }
]

// 计算属性：判断企业信息是否已通过审核
const isProfileApproved = computed(() => {
  return companyStore.profile && companyStore.profile.status === 1
})

// 获取当前用户信息
const fetchUserInfo = async () => {
  try {
    const user = await authStore.fetchCurrentUser()
    userInfo.value = user
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 检查企业信息是否完善
const checkProfileComplete = async () => {
  try {
    const profile = await companyStore.fetchProfile()
    profileComplete.value = !!profile && !!profile.name
    // 如果信息未完善且不在完善信息页面，则跳转到完善信息页面
    if (!profileComplete.value &&
        !route.path.includes('/company/profile-setup') &&
        !route.path.includes('/company/profile-review')) {
      router.push('/company/profile-setup')
    }
  } catch (error) {
    // 如果获取企业信息失败，也跳转到完善信息页面
    if (!route.path.includes('/company/profile-setup') &&
        !route.path.includes('/company/profile-review')) {
      router.push('/company/profile-setup')
    }
  }
}

// 监听路由变化，设置激活菜单项
const updateActiveMenu = () => {
  activeMenu.value = route.path
}

// 检查路由权限
const checkRoutePermission = async () => {
  // 需要审核通过才能访问的路径
  const restrictedPaths = [
    '/company/positions',
    '/company/applications',
    '/company/evaluations'
  ]

  const isRestrictedRoute = restrictedPaths.some(path => route.path.includes(path))

  if (isRestrictedRoute) {
    try {
      const profile = await companyStore.fetchProfile()
      // 如果企业信息未通过审核，重定向到企业信息页面
      if (profile.status !== 1) {
        ElMessage.warning('请先完善企业信息并通过审核后再使用此功能')
        router.push('/company/profile')
      }
    } catch (error) {
      console.error('检查权限失败:', error)
    }
  }
}

// 处理菜单选择
const handleSelect = (index) => {
  router.push(index)
}

// 用户登出
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '确认登出', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 清除本地存储的认证信息
    localStorage.removeItem('token')
    sessionStorage.removeItem('user')

    // 直接跳转到登录页
    router.push('/login')

    ElMessage.success('已退出登录')
  } catch (error) {
    // 用户取消操作
    if (error !== 'cancel') {
      ElMessage.error('登出失败: ' + (error.message || '未知错误'))
    }
  }
}

// 监听路由变化
watch(() => route.path, () => {
  updateActiveMenu()
  checkRoutePermission()
})

// 组件挂载时执行
onMounted(async () => {
  await fetchUserInfo()
  await checkProfileComplete()
  updateActiveMenu()
  checkRoutePermission()
})
</script>

<template>
  <el-container class="enterprise-layout">
    <!-- 侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '200px'" class="sidebar">
      <div class="logo" :class="{ 'collapsed': isCollapse }">
        <span v-if="!isCollapse">实习管理系统</span>
        <span v-else>IS</span>
      </div>

      <el-menu
        :default-active="$route.path"
        :collapse="isCollapse"
        background-color="#28a745"
        text-color="#ffffff"
        active-text-color="#ffd04b"
        @select="handleSelect"
        class="sidebar-menu"
      >
        <el-menu-item
          v-for="item in menuItems"
          :key="item.index"
          :index="item.index"
        >
          <el-icon>
            <component :is="item.icon" />
          </el-icon>
          <template #title>{{ item.title }}</template>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 主体区域 -->
    <el-container class="main-container">
      <!-- 头部 -->
      <el-header class="header">
        <div class="header-left">
          <el-button
            link
            @click="isCollapse = !isCollapse"
            class="collapse-button"
          >
            <el-icon>
              <component :is="isCollapse ? Expand : Fold" />
            </el-icon>
          </el-button>
        </div>

        <div class="header-right">
          <el-dropdown>
            <span class="user-info">
              <el-icon class="user-avatar"><UserFilled /></el-icon>
              <span class="username">企业用户</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="$router.push('/company/profile')">
                  <el-icon><User /></el-icon>企业信息
                </el-dropdown-item>
                <el-dropdown-item @click="handleLogout" divided>
                  <el-icon><SwitchButton /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 内容区域 -->
      <el-main class="main-content">
        <router-view></router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<style scoped>
.enterprise-layout {
  height: 100vh;
  width: 100vw;
  position: fixed;
  top: 0;
  left: 0;
  overflow: hidden;
}

.main-container {
  flex-direction: column;
  height: 100%;
}

.sidebar {
  background-color: #28a745;
  transition: width 0.3s;
  overflow: hidden;
  height: 100%;
}

.logo {
  height: 60px;
  line-height: 60px;
  text-align: center;
  color: white;
  font-size: 18px;
  font-weight: bold;
  background-color: #218838;
  transition: all 0.3s;
}

.logo.collapsed {
  font-size: 14px;
}

.sidebar-menu {
  border-right: none;
  height: calc(100% - 60px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  border-bottom: 1px solid #e6e6e6;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
}

.collapse-button {
  font-size: 20px;
  color: #606266;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.user-avatar {
  font-size: 30px;
}

.username {
  margin-left: 10px;
  font-size: 14px;
  color: #606266;
}

.main-content {
  background-color: #f5f5f5;
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}
</style>
